import React, { useState, useRef, useEffect } from 'react';
import './Setting.css'; // 引入样式文件
import { getMyprofile } from '../api/userApi';
import { updateUserProfile } from '../api/userApi';
import axiosInstance from '../api/axiosInstance';
import { loadUserProfile } from '../api/userApi';
import defaultAvatar from '../assets/images/默认头像.jpg';

const Setting = () => {
    const [image, setImage] = useState(null);
    const [imageName, setImageName] = useState(''); // 新增状态来存储图片
    const [account, setNickname] = useState('');
    const [password, setPassword] = useState('');
    const [signature, setBio] = useState('');
    const [sex, setGender] = useState(''); // 性别状态，默认为男性
    const fileInputRef = useRef(null); // 用于控制文件选择框
    const [userId, setUserId] = useState(null); // 新增 userId 状态
    const [userProfile, setUserProfile] = useState(null);

    useEffect(() => {
        const storedUserId = localStorage.getItem('userId');
        if (storedUserId) {
          setUserId(storedUserId);
        } 
    }, []);

    const handleAvatarChange = (e) => {
        const selectedImage = e.target.files[0];
    
        if (selectedImage) {
            setImage(selectedImage);
            setImageName(selectedImage); // 保存图片
            const imageUrl = URL.createObjectURL(selectedImage); // 创建临时 URL
            setImage(imageUrl); // 显示上传的图片
            alert('头像上传成功');
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
    
        try {
            // 在这里使用当前头像的文件对象，如果没有则设为 null
            const updatedProfile = await updateUserProfile(userId, account, password, sex, signature, imageName || null);
            await updateUserProfile(userId, account, password, sex, signature, imageName || null);
            //setImage(updatedProfile.image ? `${axiosInstance.defaults.baseURL}/${updatedProfile.image}` : defaultAvatar);
            alert('用户信息修改成功');
            await loadUserProfile(userId, setUserProfile);
        } catch (error) {
            alert('修改失败，请重试');
        }
    };

    // 获取个人信息
    useEffect(() => {
        const fetchUserProfile = async () => {
            try {
                const userProfile = await getMyprofile(userId);
                if (userProfile) {
                    setNickname(userProfile.account || '');
                    setPassword(userProfile.password || '');
                    setBio(userProfile.signature || '');
                    setGender(userProfile.sex || '');
                    setImage( userProfile.image ? 'http://localhost:8080/'+userProfile.image : null);  // 如果有头像，设置头像 URL
                    console.log(userProfile.image);
                    await loadUserProfile(userId, setUserProfile);
                }
            } catch (error) {
                console.error('Error fetching user profile:', error);
            }
        };

        fetchUserProfile();
    }, [userId]);  // 当 userId 变化时重新请求
    
    const handleAvatarClick = () => {
        fileInputRef.current.click(); // 触发文件选择框
    };

    return (
        <div className="setting">
            <div className="setting-profile">
            {/* {userProfile && <div>{}</div>} */}
                <p style={{fontSize:"25px", fontWeight:"bold", color:"#818181", display:"flex", marginLeft:"5%"}}>账号设置</p>
                {/* 头像上传 */}
                <div className="setting-profile-avatar">
                    <p style={{marginLeft:"5%", marginRight:"10%"}}>头像</p>
                    <input
                        ref={fileInputRef}
                        type="file"
                        accept="image/*"
                        onChange={handleAvatarChange}
                        className="setting-avatar-upload"
                        style={{ display: "none" }} // 隐藏文件输入框
                    />
                    <img
                        //src={userProfile.image ? image : defaultAvatar}
                        src={image || defaultAvatar}
                        //src={userProfile?.image || image || "https://www.w3schools.com/w3images/avatar2.png"}
                        alt="User Avatar"
                        className="setting-avatar-image"
                    />
                    <button type="button" className="form-submit-image" onClick={handleAvatarClick}>上传头像</button>
                </div>
                {/* 个人信息设置表单 */}
                <div className="setting-profile-info">
                    <form onSubmit={handleSubmit}>
                    {/* 昵称 */}
                        <div className="form-group1">
                            <label htmlFor="account" className="form-label1" style={{fontSize:"18px"}}>昵称</label>
                            <input
                                type="text"
                                id="account"
                                value={account}
                                onChange={(e) => setNickname(e.target.value)}
                                className="form-input1"
                                placeholder="请输入昵称"
                            />
                        </div>
                        {/* 密码 */}
                        <div className="form-group1">
                            <label htmlFor="password" className="form-label1" style={{fontSize:"18px"}}>密码</label>
                            <input
                                type="password"
                                id="password"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                className="form-input1"
                                placeholder="请输入新密码"
                            />
                        </div>
                        {/* 性别 */}
                        <div className="form-group1">
                            <label className="form-label1" style={{fontSize:"18px", width:"15%"}}>性别</label>
                            <div className="gender-options">
                                <label>
                                <input
                                    type="radio"
                                    name="sex"
                                    value="男"
                                    checked={sex === '男'}
                                    onChange={() => setGender('男')}
                                />
                                男
                                </label>
                                <label>
                                <input
                                    type="radio"
                                    name="sex"
                                    value="女"
                                    checked={sex === '女'}
                                    onChange={() => setGender('女')}
                                />
                                女
                                </label>
                                <label>
                                <input
                                    type="radio"
                                    name="sex"
                                    value="other"
                                    checked={sex === 'other'}
                                    onChange={() => setGender('other')}
                                />
                                秘密
                                </label>
                            </div>
                        </div>
                        {/* 个人简介 */}
                        <div className="form-group1">
                            <label htmlFor="signature" className="form-label1" style={{fontSize:"18px", width:"14%"}}>简介</label>
                            <textarea
                                id="signature"
                                value={signature}
                                onChange={(e) => setBio(e.target.value)}
                                className="form-textarea"
                                placeholder="请输入个人简介"
                            />
                        </div>
                        {/* 提交按钮 */}
                        <button type="submit" className="form-submit-btn1" style={{fontSize:"18px"}}>保存修改</button>
                    </form>
              </div>
          </div>
      </div>
    );
};

export default Setting;
